package com.example.experiment4

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.View
import android.widget.GridLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.experiment4.databinding.ActivityFlipGameBinding

class FlipGameActivity : AppCompatActivity() {
    private lateinit var binding: ActivityFlipGameBinding
    private lateinit var model: GameModel
    private val handler = Handler(Looper.getMainLooper())

    private val gridButtons = mutableListOf<TextView>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityFlipGameBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnRestart.setOnClickListener { startNewGame() }

        setupGrid()
        startNewGame()
    }

    private fun setupGrid() {
        val grid = binding.grid
        gridButtons.clear()
        grid.removeAllViews()
        val size = 4
        grid.columnCount = size
        grid.rowCount = size
        val total = size * size
        repeat(total) { index ->
            val tv = TextView(this).apply {
                layoutParams = GridLayout.LayoutParams().also { lp ->
                    lp.width = 0
                    lp.height = 0
                    lp.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
                    lp.rowSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
                    lp.setMargins(8, 8, 8, 8)
                }
                text = getString(R.string.card_back)
                gravity = Gravity.CENTER
                textSize = 24f
                isClickable = true
                // 使用默认背景即可，避免依赖内部资源
                contentDescription = getString(R.string.content_card, index + 1)
                setOnClickListener { onCardClicked(index) }
            }
            grid.addView(tv)
            gridButtons.add(tv)
        }
    }

    private fun startNewGame() {
        val symbols = resources.getStringArray(R.array.card_symbols).toList()
        model = GameModel(symbols)
        // 初始化界面
        for (i in gridButtons.indices) {
            val view = gridButtons[i]
            view.isEnabled = true
            view.text = getString(R.string.card_back)
        }
        binding.tvMoves.text = getString(R.string.text_moves, 0)
        binding.tvMatches.text = getString(R.string.text_matches, 0, model.cards.size / 2)
        binding.tvScore.text = getString(R.string.text_score, 0)
        binding.tvBest.text = getString(R.string.text_best_score, PlayerRepository.getInfo().bestScore)
    }

    private fun onCardClicked(position: Int) {
        val result = model.flip(position)
        when (result) {
            is FlipResult.None, FlipResult.First -> {
                // 只需翻开当前牌
                updateCardFace(position)
            }
            is FlipResult.Match -> {
                // 找到匹配
                updateAllCards()
            }
            is FlipResult.Mismatch -> {
                updateAllCards()
                // 短暂显示后翻回去
                handler.postDelayed({
                    model.cards[result.first].isFaceUp = false
                    model.cards[result.second].isFaceUp = false
                    updateAllCards()
                }, 600)
            }
        }
        binding.tvMoves.text = getString(R.string.text_moves, model.moves)
        binding.tvMatches.text = getString(R.string.text_matches, model.matches, model.cards.size / 2)
        binding.tvScore.text = getString(R.string.text_score, model.currentScore())

        if (model.allMatched()) {
            // 更新最佳分
            val score = model.currentScore()
            PlayerRepository.updateBestScore(score)
            binding.tvBest.text = getString(R.string.text_best_score, PlayerRepository.getInfo().bestScore)
            binding.tvCongrats.visibility = View.VISIBLE
        } else {
            binding.tvCongrats.visibility = View.GONE
        }
    }

    private fun updateCardFace(index: Int) {
        val card = model.cards[index]
        val tv = gridButtons[index]
        if (card.isFaceUp) {
            tv.text = card.symbol
        } else {
            tv.text = getString(R.string.card_back)
        }
        tv.isEnabled = !card.isMatched
        tv.alpha = if (card.isMatched) 0.5f else 1f
    }

    private fun updateAllCards() {
        for (i in model.cards.indices) {
            updateCardFace(i)
        }
    }
}


